<?php
/**
 * Created by PhpStorm.
 * User: dreamy
 * Date: 2019-05-25
 * Time: 11:16
 */
namespace common\services;

use common\models\TallyLog;
use Yii;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * Class TallyLogService
 * @package common\services
 * 日志相关
 */
class TallyLogService extends BaseService
{
    /**
     * @param $tallyId int 账本ID
     * @param int $uid int 用户ID
     * @return mixed
     */
    public static function getByTallyId($tallyId,$uid=0)
    {
        $where = [
            'tally_id'    => $tallyId,
        ];
        if($uid){
            $where['uid'] = $uid ; //uid可选
        }
        $where['type'] = 1;
        $query = TallyLog::find()
            ->select('*')
            ->orderBy('id desc')
            ->where($where);
        // 分页相关
        $count = $query->count();
        // 构造分页对象
        $pageSize = $_SERVER['PAGE_SIZE'] ?: 10 ;
        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);
        $pagination->validatePage=false;
        $list = $query
                ->offset($pagination->offset)
                ->limit($pagination->limit)
                ->all();
        return [
            'data'       => $list,
            'pageInfo'   => [
                'totalCount' => intval($count) ,
                'pageSize'   => intval($pageSize)
            ]
        ];
    }

    /**
     * @param $formData
     * @return bool
     * @desc 创建日志记录
     */
    public static function create($formData)
    {
        $model = new TallyLog();
        $model->load($formData,'');
        if ($model->validate() && $model->save()) {
            return true ;
        }else{
            Yii::error('TallyLog insert error:'.current($model->getFirstErrors()).';post:'.Json::encode($formData,JSON_UNESCAPED_UNICODE));
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

    /**
     * @param $condition
     * @return bool
     * @throws
     */
    public static function delete($condition)
    {
        $model = TallyLog::find()->where($condition)->one();
        if(!$model){
            self::setError('记录不存在');
            return false ;
        }
        if ($model->delete()) {
            return true ;
        }else{
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

}
